package com.yunhai.ucenter.config.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity( prePostEnabled = true )
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;


    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


    /**
     增加 springsecurity 配置
     */
    @Override
    protected void configure( HttpSecurity http ) throws Exception {

        //关闭 csrf。
        http.csrf().disable();

        //不通过 session 获取 securityContext
        http.sessionManagement().sessionCreationPolicy( SessionCreationPolicy.STATELESS )
        .and().authorizeRequests()
        //设置白名单，即不需要登录就可以访问的接口;
        .antMatchers("/auth/**").permitAll()
        //除了上面的所有请求以外，全部需要鉴权认证。
        .anyRequest().authenticated();


        //将 filter 加入到 springsecurity 的 fliter 过滤器链中，且在 UsernamePasswordAuthenticationFilter 之前。
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }

}
